import sys
import uvicorn
from app import app
from jqdatasdk import auth
import os

def check_jqdata_auth():
    """检查JQData认证是否成功"""
    try:
        auth("15810829938", "123QWEqwe")
        print("JQData认证成功！")
        return True
    except Exception as e:
        print(f"JQData认证失败: {e}")
        return False

def run_server():
    """运行HTTP服务器"""
    try:
        # 检查JQData认证
        if not check_jqdata_auth():
            print("由于JQData认证失败，服务无法启动。")
            sys.exit(1)
            
        # 检查是否有SSL证书文件
        ssl_keyfile = os.environ.get("SSL_KEYFILE", "")
        ssl_certfile = os.environ.get("SSL_CERTFILE", "")
        
        # 确定使用的协议
        protocol = "https" if ssl_keyfile and ssl_certfile else "http"
        
        # 启动FastAPI应用
        print(f"正在启动JQData {protocol.upper()}服务...")
        print(f"API文档: {protocol}://localhost:9001/docs")
        print(f"另一个API文档: {protocol}://localhost:9001/redoc")
        
        if protocol == "https":
            uvicorn.run(
                app, 
                host="0.0.0.0", 
                port=8000
            )
        else:
            uvicorn.run(app, host="0.0.0.0", port=9001)
    except Exception as e:
        print(f"服务启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    run_server() 